package com.ilikesoup.instant.split;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.ForkJoinWorkerThread;

/**
 * 创建带任务名称的ForkJoinPool, 对于UNCAUGHT_EXCEPTION采用日志记录的策略
 */
public class ForkJoinPoolUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(ForkJoinPoolUtils.class);

    public static final Thread.UncaughtExceptionHandler LOGGER_UNCAUGHT_EXCEPTION_HANDLER = new LoggerUncaughtExceptionHandler();

    /**
     * 使用带任务名称的ForkJoinPool线程来并行地执行任务
     * @param task  被执行任务
     * @param taskName  任务名称，会在创建线程的时候写入线程名称
     * @param <V>   返回值
     * @return
     */
    public static <V> V parallelExecuteBatch(ForkJoinTask<V> task, String taskName) {
        return parallelExecuteBatch(ForkJoinPoolUtils.create(taskName), task);
    }

    /**
     * 使用指定的ForkJoinPool并行地执行任务
     * @param forkJoinPool
     * @param task  被执行任务
     * @param <V>   返回值
     * @return
     */
    public static <V> V parallelExecuteBatch(ForkJoinPool forkJoinPool, ForkJoinTask<V> task) {
        ForkJoinTask<V> future = forkJoinPool.submit(task);
        try {
            return future.get();
        } catch (InterruptedException e) {
            LOGGER.error("批量任务执行被打断", e);
        } catch (ExecutionException e) {
            LOGGER.error("批量任务执行异常", e);
        } finally {
            forkJoinPool.shutdown();
        }
        return null;
    }

    public static ForkJoinPool create(String taskName) {
        return create(Math.min(0x7fff, Runtime.getRuntime().availableProcessors()), taskName,false);
    }

    public static ForkJoinPool create(int parallelism, String taskName) {
        return create(parallelism, taskName,false);
    }

    public static ForkJoinPool create(int parallelism, String taskName, boolean asyncModel) {
        return new ForkJoinPool(parallelism,
                new NamedForkJoinWorkerThreadFactory(taskName),
                LOGGER_UNCAUGHT_EXCEPTION_HANDLER,
                asyncModel);
    }


    private static class NamedForkJoinWorkerThread extends ForkJoinWorkerThread {
        public NamedForkJoinWorkerThread(ForkJoinPool pool, String name) {
            super(pool);
            setName(name);
        }
    }

    private static class NamedForkJoinWorkerThreadFactory implements ForkJoinPool.ForkJoinWorkerThreadFactory {
        private int id;
        private final String taskName;

        public NamedForkJoinWorkerThreadFactory(String taskName) {
            this.taskName = taskName;
            this.id = 0;
        }

        @Override
        public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
            return new NamedForkJoinWorkerThread(pool, taskName.concat("-").concat(String.valueOf(id++)));
        }
    }

    private static class LoggerUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
        private static Logger LOGGER = LoggerFactory.getLogger(LoggerUncaughtExceptionHandler.class);
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            LOGGER.error("并行任务["+ t.getName() +"]执行失败", e);
        }
    }
}
